package com.tebiecloud.goods.server.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.model.PageResult;
import com.tebiecloud.common.utils.BeanConvertUtils;
import com.tebiecloud.common.utils.RedisUtils;
import com.tebiecloud.common.utils.StringUtils;
import com.tebiecloud.goods.client.constants.GoodsConstants;
import com.tebiecloud.goods.client.model.entity.*;
import com.tebiecloud.goods.client.model.vo.*;
import com.tebiecloud.goods.server.service.*;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.goods.server.service.feign.StoreServiceClient;
import com.tebiecloud.goods.server.utils.EquipmentNoUtils;
import com.tebiecloud.store.client.model.entity.Store;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;


import javax.swing.text.html.parser.Entity;
import java.util.Arrays;

import java.util.Date;
import java.util.List;


/**
 * 商品表 前端控制器
 * @author tebie
 * @date 2019-09-23
 */
@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsSpecificationService goodsSpecificationService;

    @Autowired
    private StoreServiceClient storeServiceClient;

    @Autowired
    private GoodsCategoryService goodsCategoryService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private  GoodsNoticeService goodsNoticeService;

    @Autowired
    private  GoodsProcessService goodsProcessService;



    /**
     * 首页获取商品列表
     * @param page
     * @param limit
     * @param storeId
     * @return
     */
    @PostMapping(value = "list")
    public ResultBody<IPage<Goods>> list(
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "storeId", required = false) Long storeId) {
        if(storeId==null){
            //查询随意一家门店
            ResultBody<List<Store>> storeResultBody = storeServiceClient.list();
            if(storeResultBody!=null && storeResultBody.getCode() == ResultEnum.OK.getCode()){
                List<Store> storeList = storeResultBody.getData();
                if(storeList.size()>0){
                    storeId = storeList.get(0).getStoreId();
                }else{
                    log.info(">>minjie,没有查询到门店");
                    return ResultBodyUtils.failed("没有查询到门店");
                }
            }
        }
        return ResultBodyUtils.ok(goodsService.listGoods(page,limit,storeId));
    }

    /**
     * 获取商品列表
     * @param page
     * @param limit
     * @param storeId
     * @return
     */
    @PostMapping(value = "listGoodsByAct")
    public ResultBody listGoodsByAct(
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "storeId", required = false) Long storeId,
            @RequestParam(value = "keyword", required = false) String keyword) {
        //获取商品列表
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("store_id",storeId);
        goodsQueryWrapper.eq("deleted",0);
        if(StringUtils.isNotEmpty(keyword))goodsQueryWrapper.like("name",keyword);
        IPage<Goods> goodsIPage = goodsService.page(new Page<>(page,limit),goodsQueryWrapper);
        PageResult<GoodsByActVO> goodsByActVOPageResult = new PageResult<>(goodsIPage);
        if(goodsIPage.getRecords()!=null && goodsIPage.getRecords().size()>0){
            List<Goods> goodsList = goodsIPage.getRecords();
            List<GoodsByActVO> goodsByActVOList = Lists.newArrayList();
            for(Goods goods:goodsList){
                GoodsByActVO goodsByActVO = new GoodsByActVO();
                goodsByActVO.setGoodsId(goods.getGoodsId());
                goodsByActVO.setGoodsName(goods.getName());
                goodsByActVO.setGoodsPic(goods.getSharePic());
                //获取规格列表
                QueryWrapper<GoodsSpecification> goodsSpecificationQueryWrapper = new QueryWrapper<>();
                goodsSpecificationQueryWrapper.eq("goods_id",goods.getGoodsId());
                goodsSpecificationQueryWrapper.eq("deleted",0);
                goodsSpecificationQueryWrapper.orderByDesc("price");
                List<GoodsSpecification> goodsSpecificationList = goodsSpecificationService.list(goodsSpecificationQueryWrapper);
                goodsByActVO.setGoodsSpecificationList(goodsSpecificationList);
                if(goodsSpecificationList!=null && goodsSpecificationList.size()>0){
                    goodsByActVO.setPrice(goodsSpecificationList.get(0).getPrice());
                }
                goodsByActVOList.add(goodsByActVO);
            }
            goodsByActVOPageResult.setRecords(goodsByActVOList);
        }
        return ResultBodyUtils.ok(goodsByActVOPageResult);
    }

    @PostMapping(value = "listbycondition")
    public ResultBody listbycondition(
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "storeId", required = false) Long storeId,
            @RequestParam(value = "keyword", required = false) String keyword) {
        //获取商品列表
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("store_id",storeId);
        goodsQueryWrapper.eq("deleted",0);
        goodsQueryWrapper.orderByDesc("ct");
        if(StringUtils.isNotEmpty(keyword))goodsQueryWrapper.like("name",keyword);
        IPage<Goods> goodsIPage = goodsService.page(new Page<>(page,limit),goodsQueryWrapper);
        PageResult<BackGoodsList> backGoodsListPageResult = new PageResult<>(goodsIPage);
        if(goodsIPage.getRecords()!=null && goodsIPage.getRecords().size()>0){
            List<Goods> goodsList = goodsIPage.getRecords();
            List<BackGoodsList> backGoodsLists = Lists.newArrayList();
            for(Goods goods:goodsList){
                BackGoodsList backGoodsList = new BackGoodsList();
                backGoodsList.setGoodsId(goods.getGoodsId());
                backGoodsList.setGoodsName(goods.getName());
                backGoodsList.setDown(goods.getDown());
                backGoodsList.setNumber(goods.getNumber());
                //获取品类
                QueryWrapper<GoodsCategory> goodsCategoryQueryWrapper = new QueryWrapper<>();
                goodsCategoryQueryWrapper.eq("category_id",goods.getCategoryId());
                GoodsCategory goodsCategory = goodsCategoryService.getOne(goodsCategoryQueryWrapper);
                if(goodsCategory!=null) backGoodsList.setCategoryName(goodsCategory.getName());
                //获取规格列表
                QueryWrapper<GoodsSpecification> goodsSpecificationQueryWrapper = new QueryWrapper<>();
                goodsSpecificationQueryWrapper.eq("goods_id",goods.getGoodsId());
                goodsSpecificationQueryWrapper.eq("deleted",0);
                goodsSpecificationQueryWrapper.orderByDesc("price");
                List<GoodsSpecification> goodsSpecificationList = goodsSpecificationService.list(goodsSpecificationQueryWrapper);
                int salesVolume = 0;
                if(goodsSpecificationList!=null && goodsSpecificationList.size()>0){
                    backGoodsList.setPrice(goodsSpecificationList.get(goodsSpecificationList.size()-1).getPrice());
                    backGoodsList.setRetailPrice(goodsSpecificationList.get(goodsSpecificationList.size()-1).getRetailPrice());
                    for(GoodsSpecification goodsSpecification:goodsSpecificationList){
                        salesVolume = salesVolume + goodsSpecification.getSalesVolume();
                    }
                }
                backGoodsList.setSalesVolume(salesVolume);
                backGoodsList.setCt(goods.getCt());
                backGoodsLists.add(backGoodsList);
            }
            backGoodsListPageResult.setRecords(backGoodsLists);
        }
        return ResultBodyUtils.ok(backGoodsListPageResult);
    }

    /**
     *
     * @param goodsId
     * @return
     */
    @PostMapping("info")
    public ResultBody<GoodsVO> info(@RequestParam("goodsId") long goodsId,
                                    @RequestParam(value = "actId",required = false) Long actId) {
        return ResultBodyUtils.ok(goodsService.info(goodsId,actId));
    }

    /**
     * 新增商品
     * @param storeId 所属门店id,
     * @param name 商品名称,
     * @param carouselPics 轮播图,
     * @param detailPics 详情图,
     * @param categoryId 分类id,
     * @param down 上下架状态：0上架，1下架,
     * @param specificationlist 规格列表
     * @param   serviceEffect    服务功效
     * @param servicePart  服务部位
     * @param serviceProcess 服务流程
     * @param  effectiveTime 有效时间
     * @param  usageTime  使用时间
     * @param reservation  预约信息
     * @param applicableCrowd 适用人群
     * @param tips 温馨提示
     * @return
     */

    @PostMapping("add")
    public ResultBody add(
        @RequestParam(value = "storeId", required = false) Long storeId,
        @RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "carouselPics", required = false) String carouselPics,
        @RequestParam(value = "detailPics", required = false) String detailPics,
        @RequestParam(value = "categoryId", required = false) Long categoryId,
        @RequestParam(value = "isAnyRefund", required = false,defaultValue = "1") Integer isAnyRefund,
        @RequestParam(value = "isStoreService", required = false,defaultValue = "1") Integer isStoreService,
        @RequestParam(value = "sharePic", required = false) String sharePic,
        @RequestParam(value = "shareTitle", required = false) String shareTitle,
        @RequestParam(value = "shareRemark", required = false) String shareRemark,
        @RequestParam(value = "des", required = false) String des,
        @RequestParam(value = "down", required = false,defaultValue = "0") Integer down,
        @RequestParam(value = "specificationlist", required = false) String specificationlist,
        @RequestParam(value = "serviceEffect",required = false)String serviceEffect,
        @RequestParam(value = "servicePart",required = false)String servicePart,
        @RequestParam(value = "serviceProcess",required = false)String serviceProcess,
        @RequestParam(value = "effectiveTime",required = false)String effectiveTime,
        @RequestParam(value = "exceptTime",required = false)String exceptTime,
        @RequestParam(value = "usageTime",required = false)String usageTime,
        @RequestParam(value = "reservation",required = false)String reservation,
        @RequestParam(value = "applicableCrowd",required = false)String applicableCrowd,
        @RequestParam(value = "tips",required = false)String tips) {
        //查询一下redis

        String key = GoodsConstants.REDIS_GOODS_NUMBER_+storeId;
        String value = redisUtils.get(key);
        int goodsNum = 0;
        if(value == null){
            //查询有多少个商品
            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.eq("store_id",storeId);
            goodsNum = goodsService.count(goodsQueryWrapper);
        }else {
            goodsNum = Integer.valueOf(value);
        }
        String number = EquipmentNoUtils.getNewEquipmentNo("0000001",String.valueOf(goodsNum));
        redisUtils.set(key,number);

        Goods goods = new Goods();
        goods.setStoreId(storeId);
        if(StringUtils.isNotEmpty(carouselPics)){
            goods.setMainPic(carouselPics.split(",")[0]);
        }
        goods.setNumber(number);
        goods.setName(name);
        goods.setCarouselPics(carouselPics);
        goods.setDetailPics(detailPics);
        goods.setCategoryId(categoryId);
        goods.setGoodsType(1);//默认是服务商品
        goods.setIsAnyRefund(isAnyRefund);
        goods.setIsStoreService(isStoreService);
        goods.setSharePic(sharePic);
        goods.setShareRemark(shareRemark);
        goods.setShareTitle(shareTitle);
        goods.setDes(des);
        goods.setDown(down);
        if(goodsService.save(goods)){
            GoodsNotice goodsNotice=new GoodsNotice();
            goodsNotice.setGoodsId(goods.getGoodsId());
            goodsNotice.setTips(tips);
            goodsNotice.setEffectiveTime(effectiveTime);
            goodsNotice.setExceptTime(exceptTime);
            goodsNotice.setUsageTime(usageTime);
            goodsNotice.setReservation(reservation);
            goodsNotice.setDeleted(0);
            goodsNotice.setCt(new Date());
            goodsNotice.setApplicableCrowd(applicableCrowd);
            goodsNoticeService.save(goodsNotice);

            GoodsProcess goodsProcess=new GoodsProcess();
            goodsProcess.setGoodsId(goods.getGoodsId());
            goodsProcess.setDeleted(0);
            goodsProcess.setServiceEffect(serviceEffect);
            goodsProcess.setServicePart(servicePart);
            goodsProcess.setServiceProcess(serviceProcess);
            goodsProcess.setCt(new Date());
            goodsProcessService.save(goodsProcess);
            if(StringUtils.isEmpty(specificationlist))return ResultBodyUtils.ok();
            //字符串转对象列表
            JSONArray jsonArray = JSONArray.parseArray(specificationlist);
            List<SpecificationList> specificationLists = jsonArray.toJavaList(SpecificationList.class);
            List<GoodsSpecification> goodsSpecificationList = Lists.newLinkedList();
            for(SpecificationList specificationList:specificationLists){
                GoodsSpecification goodsSpecification = new GoodsSpecification();
                goodsSpecification.setGoodsId(goods.getGoodsId());
                goodsSpecification.setPrice(specificationList.getPrice());
                goodsSpecification.setRetailPrice(specificationList.getRetailPrice());
                goodsSpecification.setCostPrice(specificationList.getRetailPrice());
                goodsSpecification.setCommissionRate(specificationList.getCommissionRate());
                goodsSpecification.setDown(1);
                goodsSpecification.setName(specificationList.getSpecName());
                goodsSpecification.setGoodsProcessId(goodsProcess.getGoodsProcessId());
                goodsSpecification.setStockQty(-99);
                goodsSpecification.setDeleted(0);
                goodsSpecificationList.add(goodsSpecification);
            }
            goodsSpecificationService.saveBatch(goodsSpecificationList);
        }
        return ResultBodyUtils.ok();
    }

    /**
     * 更新数据
     * @param goodsId 所属门店id
     * @param name 商品名称
     * @param carouselPics 轮播图
     * @param detailPics 详情图
     * @param categoryId 分类id
     * @param down 上下架状态：0上架，1下架
     * @return
     */
    @PostMapping("update")
    public ResultBody update(
            @RequestParam(value = "goodsId", required = false) Long goodsId,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "carouselPics", required = false) String carouselPics,
            @RequestParam(value = "detailPics", required = false) String detailPics,
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "isAnyRefund", required = false,defaultValue = "1") Integer isAnyRefund,
            @RequestParam(value = "isStoreService", required = false,defaultValue = "1") Integer isStoreService,
            @RequestParam(value = "sharePic", required = false) String sharePic,
            @RequestParam(value = "shareTitle", required = false) String shareTitle,
            @RequestParam(value = "shareRemark", required = false) String shareRemark,
            @RequestParam(value = "des", required = false) String des,
            @RequestParam(value = "down", required = false,defaultValue = "0") Integer down,
            @RequestParam(value = "specificationlist", required = false) String specificationlist) {
        Goods goods = new Goods();
        if(StringUtils.isNotEmpty(carouselPics)){
            goods.setMainPic(carouselPics.split(",")[0]);
        }
        goods.setName(name);
        goods.setCarouselPics(carouselPics);
        goods.setDetailPics(detailPics);
        goods.setCategoryId(categoryId);
        goods.setIsAnyRefund(isAnyRefund);
        goods.setIsStoreService(isStoreService);
        goods.setSharePic(sharePic);
        goods.setShareRemark(shareRemark);
        goods.setShareTitle(shareTitle);
        goods.setDes(des);
        goods.setDown(down);
        goodsService.updateById(goods);
        //跟新规格
        if(StringUtils.isEmpty(specificationlist))return ResultBodyUtils.ok();
        //字符串转对象列表
        JSONArray jsonArray = JSONArray.parseArray(specificationlist);
        List<SpecificationList> specificationLists = jsonArray.toJavaList(SpecificationList.class);
        for(SpecificationList specificationList:specificationLists){
            if(specificationList.getSpecId()!=null){
                GoodsSpecification goodsSpecification = new GoodsSpecification();
                goodsSpecification.setSpecId(specificationList.getSpecId());
                goodsSpecification.setPrice(specificationList.getPrice());
                goodsSpecification.setRetailPrice(specificationList.getRetailPrice());
                goodsSpecification.setCostPrice(specificationList.getRetailPrice());
                goodsSpecification.setCommissionRate(specificationList.getCommissionRate());
                goodsSpecification.setName(specificationList.getSpecName());
                goodsSpecificationService.updateById(goodsSpecification);
            }else {
                GoodsSpecification goodsSpecification = new GoodsSpecification();
                goodsSpecification.setGoodsId(goodsId);
                goodsSpecification.setPrice(specificationList.getPrice());
                goodsSpecification.setRetailPrice(specificationList.getRetailPrice());
                goodsSpecification.setCostPrice(specificationList.getRetailPrice());
                goodsSpecification.setCommissionRate(specificationList.getCommissionRate());
                goodsSpecification.setDown(1);
                goodsSpecification.setName(specificationList.getSpecName());
                goodsSpecification.setStockQty(-99);
                goodsSpecification.setDeleted(0);
                goodsSpecificationService.save(goodsSpecification);
            }
        }
        return ResultBodyUtils.ok();
    }

    /**
     * 商品详情
     * @param goodsId
     * @return
     */
    @PostMapping("goodsDetail")
    public ResultBody goodsDetail(@RequestParam("goodsId") long goodsId) {
        //获取商品信息
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("goods_id",goodsId);
        Goods goods = goodsService.getOne(goodsQueryWrapper);
        if(goods==null)return ResultBodyUtils.failedMsg("查询商品不存在");
        //获取规格信息
        QueryWrapper<GoodsSpecification> goodsSpecificationQueryWrapper = new QueryWrapper<>();
        goodsSpecificationQueryWrapper.eq("goods_id",goodsId);
        goodsSpecificationQueryWrapper.eq("deleted",0);
        List<GoodsSpecification> goodsSpecificationList = goodsSpecificationService.list(goodsSpecificationQueryWrapper);
        GoodsDetailVO goodsDetailVO = BeanConvertUtils.convertBean(goods,GoodsDetailVO.class);
        goodsDetailVO.setGoodsSpecificationList(goodsSpecificationList);
        return ResultBodyUtils.ok(goodsDetailVO);
    }
    /**
     * 删除数据
     * @param id 单个id
     * @param ids 多个id用,号隔开
     * @return
     */
    @PostMapping("remove")
    public ResultBody remove(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "ids", required = false) String ids
    ) {
        if(id != null && id > 0) {
            goodsService.removeById(id);
        }
        if(ids != null && ids.length() > 0) {
            goodsService.removeByIds(Arrays.asList(ids.split(",")));
        }
        return ResultBodyUtils.ok();
    }

}
